package org.example.doctorapi.sms;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.example.doctorapi.data.HisVerificationCode;
import org.example.doctorapi.mapper.HisVerificationCodeMapper;
import org.example.doctorapi.util.IdGeneration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
public class VerficationCodeServiceImp implements VerficationCodeService{
    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private HisVerificationCodeMapper hisVerificationCodeMapper;
    @Override
    public int SendSms(String phoneNumber) {
        Integer code = IdGeneration.generateVerificationCode();
        String result =  this.execute(phoneNumber,code);
        JSONObject jsonObject = (JSONObject)JSON.parse(result);
        if (jsonObject !=null && StringUtils.isNoneEmpty(jsonObject.getString("respCode"))){
            if (jsonObject.getString("respCode").equals("0000")){
                return saveVerification(phoneNumber,code);
            }
        }
        return -1;
    }

    @Override
    public HisVerificationCode checkCode(String phoneNumber, Integer code) {
        QueryWrapper<HisVerificationCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone_number",phoneNumber);
        queryWrapper.eq("verification_code",code);
        queryWrapper.eq("is_check",0);
        return hisVerificationCodeMapper.selectOne(queryWrapper);
    }

    @Override
    public void isCheckCode(HisVerificationCode hisVerificationCode) {
        hisVerificationCode.setIsCheck(1);
        hisVerificationCodeMapper.updateById(hisVerificationCode);
    }

    private int saveVerification(String phoneNumber, Integer code) {
        HisVerificationCode verificationCode = new HisVerificationCode();
        verificationCode.setPhoneNumber(phoneNumber);
        verificationCode.setVerificationCode(code);
        verificationCode.setCreateTime(DateUtil.date());
        verificationCode.setIsCheck(0);
        hisVerificationCodeMapper.insert(verificationCode);
        return 1;
    }

    private String execute(String phoneNumber,Integer code) {
        String builder = "accoundSid" + "=" + smsConfig.getACCOUNT_SID() +
                "&to" + "=" + phoneNumber +
                "templateid" + "=" + smsConfig.getTEMPLATE_ID() +
                "$param" + "=" + URLEncoder.encode(code.toString(), StandardCharsets.UTF_8);
        String body =  builder + smsConfig.createCommonParam(smsConfig.getACCOUNT_SID(),smsConfig.getAUTH_TOKEN());
        return IdGeneration.post(smsConfig.getBASE_URL(),body);
    }
}
